import pygame
import random

# 初始化 Pygame
pygame.init()

# 定义常量
WIDTH = 800
HEIGHT = 600
WHITE = (255, 255, 255)
BLUE = (0, 0, 255)
RED = (255, 0, 0)

# 创建游戏窗口
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("捕鱼游戏")

# 鱼的类
class Fish(pygame.sprite.Sprite):
    def __init__(self):
        super().__init__()
        self.image = pygame.Surface((50, 30))
        self.image.fill(RED)
        self.rect = self.image.get_rect()
        self.rect.x = random.randint(WIDTH, WIDTH + 200)
        self.rect.y = random.randint(0, HEIGHT - self.rect.height)
        self.speed = random.randint(2, 5)

    def update(self):
        self.rect.x -= self.speed
        if self.rect.right < 0:
            self.rect.x = random.randint(WIDTH, WIDTH + 200)
            self.rect.y = random.randint(0, HEIGHT - self.rect.height)
            self.speed = random.randint(2, 5)

# 子弹的类
class Bullet(pygame.sprite.Sprite):
    def __init__(self, x, y):
        super().__init__()
        self.image = pygame.Surface((10, 5))
        self.image.fill(BLUE)
        self.rect = self.image.get_rect()
        self.rect.centerx = x
        self.rect.centery = y
        self.speed = 8

    def update(self):
        self.rect.x += self.speed
        if self.rect.left > WIDTH:
            self.kill()

# 创建精灵组
all_sprites = pygame.sprite.Group()
fish_group = pygame.sprite.Group()
bullet_group = pygame.sprite.Group()

# 创建鱼
for _ in range(5):
    fish = Fish()
    all_sprites.add(fish)
    fish_group.add(fish)

# 炮台位置
cannon_x = 20
cannon_y = HEIGHT // 2

# 得分
score = 0
font = pygame.font.Font(None, 36)

# 游戏主循环
clock = pygame.time.Clock()
running = True
while running:
    screen.fill(WHITE)

    # 处理事件
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.MOUSEBUTTONDOWN:
            bullet = Bullet(cannon_x, cannon_y)
            all_sprites.add(bullet)
            bullet_group.add(bullet)

    # 更新精灵
    all_sprites.update()

    # 碰撞检测
    hits = pygame.sprite.groupcollide(fish_group, bullet_group, True, True)
    for _ in hits:
        score += 10

    # 绘制炮台
    pygame.draw.rect(screen, BLUE, (cannon_x, cannon_y - 20, 20, 40))

    # 绘制精灵
    all_sprites.draw(screen)

    # 显示得分
    score_text = font.render(f"得分: {score}", True, BLUE)
    screen.blit(score_text, (10, 10))

    # 更新显示
    pygame.display.flip()
    clock.tick(60)

# 退出游戏
pygame.quit()